package org.example.websocket1.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.websocket1.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Controller
public class MessageController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private SessionRegistry sessionRegistry;

    @MessageMapping("/sendAll")
    public void sendAll(String message) throws JsonProcessingException {
        List<Object> list = sessionRegistry.getAllPrincipals();
        System.out.println(list);
        List<String> users = new ArrayList<>();
        for(Object o:list){
            User user = (User) o;
            users.add(user.getUsername());
        }
        messagingTemplate.convertAndSend("/topic/receiveAll",users);
    }

    @GetMapping("/getCurrentUser")
    @ResponseBody
    public String getCurrentUser(Principal principal) {
        System.out.println(principal.getName());
        return principal.getName();
    }

    @MessageMapping("/sendTo")
    public void sendTo(Principal principal, Message message){
        System.out.println(message);
        message.setFrom(principal.getName());
        messagingTemplate.convertAndSendToUser(message.getTo(),"/queue/receiveOne",message);
        messagingTemplate.convertAndSendToUser(message.getFrom(),"/queue/receiveOne",message);
    }
}
